package cn.lj.controller;

import cn.lj.common.handler.BusinessException;
import cn.lj.common.response.Result;
import cn.lj.common.response.ResultCode;
import cn.lj.common.util.SecretUtil;
import cn.lj.entity.LoginVo;
import cn.lj.entity.User;
import cn.lj.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.UUID;

/**
 * @file: loginController
 * @version: 1.2
 * @Description: 将登录从用户控制中分离
 * 代码目的，作用，如何工作
 * @author: 李津
 * @date: 2021-04-18 14:08
 * 本代码要注意的事项、备注事项等
 */

@RestController
@RequestMapping("//user")
//@CrossOrigin
@Api(value = "用户管理", tags = "系统用户接口")
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    @ResponseBody//RequestParam接收的是key-value里面的参数，所以它会被切面进行处理从而可以用普通元素、数组、集合、对象等接收
    @ApiOperation(value = "用户登录",notes = "登录")
    public Result login(@RequestBody User user) {
        //前端传来的加密密码进行解密
        String userPassword = SecretUtil.desEncrypt(user.getPassword());

        User userLogin = userService.findByLoginName(user.getLoginName());
        if (Objects.isNull(userLogin)) {
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }

        //查出的密码
        String password = userLogin.getPassword();

        if (!passwordEncoder.matches(userPassword,password)) {
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }

        //这里token直接用一个uuid
        //使用jwt的情况下，会生成一个jwt token,jwt token里会包含用户的信息
        LoginVo loginVo = new LoginVo();
        String token = UUID.randomUUID().toString();
        loginVo.setId(user.getId());
        loginVo.setToken(token);
        loginVo.setUser(user);
        return Result.ok().data("loginVo",loginVo);
    }

    /**
     * 注册、添加用户
     * @param user
     * @return
     */
    @ApiOperation(value = "添加用户",notes = "添加用户信息")
    @PostMapping("/addUser")
    public Result addUser(@RequestBody User user) {
        try{
            userService.addUser(user);
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error();
        }
    }

    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public Result logout() {
        return Result.ok().message("注销成功！");
    }

}
